package com.zhg.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhg.model.auto.News;
import com.zhg.model.auto.NewsAccount;
import com.zhg.service.impl.NewsServiceImpl;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 达瓦里氏
 * @since 2021-12-24
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    NewsServiceImpl newsService;

    /*查询资讯*/
    @GetMapping("/getNews")
    public List<NewsAccount> getNews(){ return newsService.SelectAllNews(); }

    /*通过id查询资讯*/
    @GetMapping("/getNewsById/{id}")
    public News getNewsById(@PathVariable("id") int id){
        return newsService.getById(id);
    }

    /*修改资讯*/
    @PostMapping("/updateNews")
    public void updateNews(@RequestBody News news){
        newsService.updateById(news);
    }

    /*添加资讯*/
    @PostMapping("/setNews")
    public void setNews(@RequestBody News news){
        newsService.save(news);
    }

    /*删除资讯*/
    @PostMapping("/deletedById/{id}")
    public boolean deleted(@PathVariable("id") int id){
        return newsService.removeById(id);
    }

    /*图片上传*/
    @PostMapping("/elupload")
    public String elUpload(MultipartFile file){
        String fileName = file.getOriginalFilename();
        System.out.println("进来了");
        File dest = new File("D:\\project\\baidu\\vue-baidu\\static\\img\\" + fileName);
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败！";
    }

    /*首页热门资讯的排序*/
    @GetMapping("/hot")
    public List<News> ListByHot(){
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("watch");
        List<News> list = newsService.list(queryWrapper);
        return list;
    }

    /*查询不同热门类别资讯的接口*/
    @GetMapping("/hotClass/{id}")
    public List<News> ListClassById(@PathVariable("id") int id){
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("watch");
        queryWrapper.eq("classId",id);
        List<News> list = newsService.list(queryWrapper);
        return list;
    }

    /*查询不同类别资讯的接口为*/
    @GetMapping("/getClass/{id}")
    public List<News> ListClass(@PathVariable("id") int id){
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classId",id);
        List<News> list = newsService.list(queryWrapper);
        return list;
    }
}
